package com.siblings.loan.ui.loan.fm

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.Typeface
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import com.lib.base.utils.DensityUtils
import com.lib.base.utils.TitleBarUtil
import com.lib.base.utils.log.LogHelper
import com.siblings.loan.R
import com.siblings.loan.utils.helper.TestDataLibInvoke
import com.siblings.loan.databinding.FmLoanLimitBinding
import com.siblings.loan.http.HttpHelper
import com.siblings.loan.ui.loan.act.SibLoanApplyAct
import com.siblings.loan.ui.loan.impl.SibLoanLimitPresenterImpl
import com.siblings.loan.ui.loan.view.ISibLoanLimitView
import com.siblings.loan.ui.tab.act.SibMainAct
import com.siblings.loan.ui.user.act.SibMessageAct
import com.siblings.loan.utils.dialog.LoanGuideDialog
import com.siblings.loan.utils.event.SibEventData
import com.siblings.loan.utils.event.SibEventType
import com.siblings.loan.utils.helper.SharedHelper
import com.siblings.loan.weight.CircleSeekBar
import com.siblings.loan.weight.ScaleRulerView.OnValueChangeListener
import com.siblings.mvp.MvpFm
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject

/**
 * SiblingsLoan
 * @Author wwdeng
 * @CreateTime: 2024/7/8 18:12
 * @Annotation：贷款额度、待还款
 */
class SibLoanLimitFm: MvpFm<ISibLoanLimitView,SibLoanLimitPresenterImpl>(),ISibLoanLimitView {
    lateinit var binding: FmLoanLimitBinding
    //是否显示去申请贷款
    private var isShowWithdraw = true

    override fun getSibRootView(inflater: LayoutInflater): View {
        binding = FmLoanLimitBinding.inflate(inflater)
        return binding.root
    }

    override fun createMvpPresenter(): SibLoanLimitPresenterImpl {
        return SibLoanLimitPresenterImpl(context)
    }

    override fun initSibView() {
        rootViewBinding.containerLayout.setBackgroundColor(Color.parseColor("#00000000"))
        binding.parentLayout.setPadding(0,TitleBarUtil.getStatusBarHeight(),0,0)

        initSibRefreshLayout()
        val colors = intArrayOf(
            Color.parseColor("#ff48af6e"),
            Color.parseColor("#ff48af6e"),
            Color.parseColor("#ff1e492e"),
            Color.parseColor("#ff1e492e"),
        )
        val positions = floatArrayOf(0f, 0.35f, 0.6f, 1.0f)
        binding.circleSeekBar.setShader(colors,positions)
    }

    override fun initSibListener() {
        //个人中心菜单
        binding.imgMenu.setOnClickListener {
            val tabAct = context as SibMainAct
            tabAct.showSibMenuFragment("Loan Limit Page")
        }
        //消息
        binding.imgMessage.setOnClickListener {
            onIntent(SibMessageAct::class.java)
        }

        binding.circleSeekBar.setOnChangeListener(object : CircleSeekBar.OnChangeListener {
            override fun onStartTrackingTouch(isCanDrag: Boolean) {
            }
            override fun onProgressChanged(progress: Float, max: Float, fromUser: Boolean) {
            }
            override fun onStopTrackingTouch(isCanDrag: Boolean) {
            }
            override fun onSingleTapUp() {
            }
        })

        //申请
        binding.btnWithdraw.setOnClickListener {
            if (!isShowWithdraw){
                //去还款
                val act = context as SibMainAct
                act.mvpPresenter.setSibCurrentItemIndex(1)
                return@setOnClickListener
            }
            //上报
            TestDataLibInvoke.sycData()
            mvpPresenter.checkSibAllPermissionsAgree()
        }
    }

    override fun initSibData() {
        showGuideDialog()
        showSibLoading()
        mvpPresenter.loadSibLoanLimitAction()
        mvpPresenter.loadSibAllPermissionsAction()
    }

    /* 初始化刷新 */
    private fun initSibRefreshLayout() {
        //禁止加载
        binding.refreshLayout.setEnableLoadMore(false)
        binding.refreshLayout.setEnableAutoLoadMore(false)
        binding.refreshLayout.setOnRefreshListener {
            //发送刷新流程通知
            EventBus.getDefault().post(SibEventData(SibEventData.TYPE.SIB_PROCESS_REFRESH))
        }
        binding.refreshLayout.setOnLoadMoreListener {
            binding.refreshLayout.finishLoadMore()
        }
    }

    /**
     * 刷新额度数据
     */
    fun onRefreshLoanLimitAction(){
        mvpPresenter.loadSibLoanLimitAction()
    }

    /**
     * 显示贷款额度信息
     */
    @SuppressLint("SetTextI18n")
    override fun showSibLoanLimitInfo(data: JSONObject) {
        //已用额度
        val utilisedAmount = data.optInt("utilisedAmount")
        //剩余可用额度
        val availableAmount = data.optInt("availableAmount")
        //总额度 = 已用额度 + 剩余可用额度
        val totalAmount = utilisedAmount + availableAmount

        binding.textMinTotalAmount.text = "0"
        binding.textMaxTotalAmount.text = "$totalAmount"

        binding.circleSeekBar.isShowPercentText = false
        binding.circleSeekBar.max = totalAmount
        binding.circleSeekBar.labelText = "$availableAmount"
        binding.circleSeekBar.showAnimation(binding.circleSeekBar.max, availableAmount, 1500)

        //最长期限
        val showText = String.format(getString(R.string.loan_limit_maximum),data.optString("days"))
        val startIndex = showText.indexOf("≥")
        val spString = SpannableString(showText)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FF4DB673")), startIndex, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textMaxTerm.text = spString

        //最小申请额度
        var minAmount = data.optInt("minAmount")
        //最大申请额度
        val maxAmount = data.optInt("maxAmount")
        //额度颗粒度
        val granularity = data.optInt("granularity")
        //最小申请额度 >= 最大申请额度
        if (minAmount >= maxAmount){
            minAmount = maxAmount
        }

        //正在使用中
        val showUseText = String.format(getString(R.string.loan_limit_in_use),"$utilisedAmount")
        binding.textInUse.text = getSibAmountStyle(showUseText,"$utilisedAmount",Color.parseColor("#FFFF9B25"))
        //剩余可用额度
        val showAvailableText = String.format(getString(R.string.loan_limit_available),"$availableAmount")
        binding.textAvailable.text = getSibAmountStyle(showAvailableText,"$availableAmount",Color.parseColor("#FF4DB673"))
        //使用进度
        binding.useSeekBar.max = totalAmount
        binding.useSeekBar.progress = availableAmount

        //剩余可用额度 <= 0
        if (availableAmount <= 0){
            //不显示修改金额板块内容，按钮显示 去还款
            binding.chooseAmountLayout.visibility = View.GONE
            binding.btnWithdraw.text = getString(R.string.btn_go_repay)
            isShowWithdraw = false
            return
        }

        //是否是渠道用户
        val isAdSource = SharedHelper.getSibSPBoolean(SharedHelper.SIB_SPKEY.SIBLINGS_IS_ADSOURCE)
        //剩余可用额度 < 最小申请额度 && 渠道用户
        if (availableAmount < minAmount && isAdSource){
            //渠道用户不可再次申请，不显示修改金额板块内容，按钮显示 去还款
            binding.chooseAmountLayout.visibility = View.GONE
            binding.btnWithdraw.text = getString(R.string.btn_go_repay)
            isShowWithdraw = false
            return
        }
        binding.chooseAmountLayout.visibility = View.VISIBLE
        binding.btnWithdraw.text = getString(R.string.btn_withdraw)

        binding.textMinAmount.text = "$minAmount"
        binding.textMaxAmount.text = "$maxAmount"
        binding.textCurtAmount.text = "$minAmount"

        binding.rulerView.setParam(
            DensityUtils.dp2px(10f), DensityUtils.dp2px(17f), DensityUtils.dp2px(17f),
            DensityUtils.dp2px(10f), DensityUtils.dp2px(9f), DensityUtils.dp2px(12f)
        )
        if (minAmount >= maxAmount){
            binding.rulerView.initViewParam(maxAmount.toFloat(), 0f, (maxAmount * 100).toFloat(), 10 * granularity)
        } else {
            binding.rulerView.initViewParam(minAmount.toFloat(), minAmount.toFloat(), maxAmount.toFloat(), 10 * granularity)
        }
        binding.rulerView.setValueChangeListener(object : OnValueChangeListener{
            override fun onValueChange(value: Float) {
                var showValue = value
                if (minAmount >= maxAmount){
                    showValue = maxAmount.toFloat()
                }
                binding.textCurtAmount.text ="${showValue.toInt()}"
            }
            override fun onValueComplete(value: Float) {
            }
        })
    }

    /**
     * 权限检查成功
     */
    override fun showSibCheckPermissionSuccess() {
        SibLoanApplyAct.start(requireContext(),binding.textCurtAmount.text.toString())
    }

    /**
     * 显示引导页
     */
    private fun showGuideDialog(){
        val isShowed = SharedHelper.getSibSPBoolean(SharedHelper.SIB_SPKEY.SIBLINGS_DIALOG_GUIDE)
        LogHelper.e(">>>>>>展示引导页>>>>>>>>>>>>>>>>>>>$isShowed")
        if (!isShowed){
            SharedHelper.saveSibSPData(SharedHelper.SIB_SPKEY.SIBLINGS_DIALOG_GUIDE,true)
            val guideDialog = LoanGuideDialog(context)
            guideDialog.setCancelable(false)
            guideDialog.setCanceledOnTouchOutside(false)
            guideDialog.show()
        }
    }

    /**
     * 设置文本样式
     */
    private fun getSibAmountStyle(showText: String,key: String,color: Int): SpannableString{
        val startIndex = showText.indexOf(key)
        val endIndex = startIndex + key.length

        val spString = SpannableString(showText)
        //改变字体颜色
        spString.setSpan(ForegroundColorSpan(color), startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //设置字体加粗
        spString.setSpan(StyleSpan(Typeface.BOLD),startIndex, endIndex, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        return spString
    }

    override fun hideSibLoading() {
        super.hideSibLoading()
        binding.refreshLayout.finishRefresh()
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addSibEventAction(SibEventType.PAGE.SIB_PAGE_LOAN_LIMIT_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addSibEventAction(SibEventType.PAGE.SIB_PAGE_LOAN_LIMIT_END,"")
    }
}